package com.xr.service;

import com.xr.pojo.Permission;
import com.xr.pojo.Role;
import com.xr.pojo.User;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class UserService implements UserDetailsService {
    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        System.out.println("登录的是"+s);
        User userFDb = findByUsername(s);
        System.out.println(userFDb);
        if (userFDb!=null){
            //存在
            //将用户信息给框架
            //由框架进行密码比对
            List<GrantedAuthority> list=new ArrayList<>();
            //后期改为查数据库
            userFDb.getRoles().forEach(r->{
                //授予角色
                list.add(new SimpleGrantedAuthority(r.getName()));
                //授予权限
                r.getPermissions().forEach(p->{
                    list.add(new SimpleGrantedAuthority(p.getName()));
                });
            });
            System.out.println("grantedAuthorities:"+list);
            org.springframework.security.core.userdetails.User user=new org.springframework.security.core.userdetails.User(s,"{noop}"+userFDb.getUserPassword(),list);
            return user;
        }else{
            //不存在
        }
        return null;
    }

    /**
     * 模拟数据库查询
     */
    private User findByUsername (String username){
        if("admin".equals(username)) {
            User user = new User();
            user.setUserName("admin");
            user.setUserPassword("admin");

            Role role = new Role();
            role.setName("ROLE_ADMIN");

            Permission permission = new Permission();
            permission.setName("ADD_CHECKITEM");
            role.getPermissions().add(permission);

            Set<Role> roleList = new HashSet<>();
            roleList.add(role);

            user.setRoles(roleList);
            return user;
        }else if("xiaoming".equals(username)){//无权限访问，403
            User user = new User();
            user.setUserName("xiaoming");
            user.setUserPassword("xm");
            return user;
        }
        return null;
    }
}
